package com.casems.intercepter;

import cn.hutool.json.JSONUtil;
import com.casems.commons.util.JwtUtil;
import com.casems.commons.vo.ResultVO;
import com.casems.entity.User;
import com.casems.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@Slf4j
public class AuthIntercepter implements HandlerInterceptor {

    public static final String OPTIONS = "options";
    public static final String HEADER_AUTHORIZATION = "Authorization";

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if(StringUtils.equals(method, OPTIONS)){
            return true;
        }
        String headerAuthorization = request.getHeader(HEADER_AUTHORIZATION);
        if(StringUtils.isEmpty(headerAuthorization)){
            return noAuth(response, "请传入认证信息");
        }
        try{
            String phone = JwtUtil.getPhone(headerAuthorization);
            User user = userService.getUser(phone);
            if(ObjectUtils.isEmpty(user)){
                throw new RuntimeException("用户名错误");
            }
            return true;
        }catch (ExpiredJwtException e){
            log.error(e.getMessage(),e);
            return noAuth(response,"认证信息已过期");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return noAuth(response,"认证信息错误");
        }

    }

    private boolean noAuth(HttpServletResponse response, String message) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        ResultVO<Object> resultVO = ResultVO.failed(401, message);
        String result = JSONUtil.toJsonStr(resultVO);

        PrintWriter writer = response.getWriter();
        writer.println(result);
        writer.close();
        return false;
    }

}
